#include "Poco/Event.h"
#include "Poco/Exception.h"
#include "BEvent.h"

using namespace SystemTool;

// Construct the obj
BEvent::BEvent()
{
    m_pEvent = new Poco::Event(Poco::Event::EVENT_MANUALRESET);
    UnSignal();
}

// Destruct the obj
BEvent::~BEvent()
{
    Signal();

    Poco::Event* pEvent = (Poco::Event*)m_pEvent;
    if(pEvent)
    {
        delete pEvent;
        m_pEvent = nullptr;
    }
}

// Set the event to signal
void BEvent::Signal()
{
    Poco::Event* pEvent = (Poco::Event*)m_pEvent;
    if(pEvent)
    {
        pEvent->set();
    }
}

// Set the event to unsignal
void BEvent::UnSignal()
{
    Poco::Event* pEvent = (Poco::Event*)m_pEvent;
    if(pEvent)
    {
        pEvent->reset();
    }
}

// Wait for the event to be signal
void BEvent::Wait(long lMs)
{
    Poco::Event* pEvent = (Poco::Event*)m_pEvent; 
    if(pEvent == nullptr)
    {
        return;
    }

    if(lMs == 0)
    {
        pEvent->wait();
        return;
    }

    try
    {
       pEvent->wait(lMs);
    }
    catch(Poco::Exception& e)
    {
        // Do nothing for timeout
    }
}
